﻿using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// 声音管理器 
/// </summary>
public class AudioMgr : UnitySingleton<AudioMgr>
{
    private Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>();
    private Dictionary<string, AudioSource> audioSources = new Dictionary<string, AudioSource>();
    private GameObject audioRoot;

    [Header("音频设置")]
    public float globalVolume = 1.0f;
    public bool mute = false;

    protected void Awake()
    {
        audioRoot = new GameObject("AudioRoot");
        audioRoot.transform.SetParent(transform);
    }

    /// <summary>
    /// 预加载音频资源
    /// </summary>
    public void PreloadAudio(string path)
    {
        if (audioClips.ContainsKey(path)) return;

        AudioClip clip = Resources.Load<AudioClip>(path);
        if (clip != null)
        {
            audioClips.Add(path, clip);
        }
    }

    /// <summary>
    /// 播放音效
    /// </summary>
    public void PlaySound(string path, float volume = 1.0f, bool loop = false)
    {
        if (mute) return;

        if (!audioClips.TryGetValue(path, out AudioClip clip))
        {
            clip = Resources.Load<AudioClip>(path);
            if (clip == null)
            {
                Debug.LogError($"Audio clip not found: {path}");
                return;
            }
            audioClips.Add(path, clip);
        }

        GameObject soundObj = new GameObject($"Sound_{path}");
        soundObj.transform.SetParent(audioRoot.transform);

        AudioSource source = soundObj.AddComponent<AudioSource>();
        source.clip = clip;
        source.volume = globalVolume * volume;
        source.loop = loop;
        source.Play();

        if (!loop)
        {
            Destroy(soundObj, clip.length);
        }
        else
        {
            audioSources.Add(path, source);
        }
    }

    /// <summary>
    /// 停止音效
    /// </summary>
    public void StopSound(string path)
    {
        if (audioSources.TryGetValue(path, out AudioSource source))
        {
            source.Stop();
            Destroy(source.gameObject);
            audioSources.Remove(path);
        }
    }

    /// <summary>
    /// 设置全局音量
    /// </summary>
    public void SetGlobalVolume(float volume)
    {
        globalVolume = Mathf.Clamp01(volume);
        foreach (var source in audioSources.Values)
        {
            source.volume = globalVolume;
        }
    }
}